#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "layerconfigdialog.h"
#include <QMessageBox>
#include <QInputDialog>
#include <QFileDialog>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
using namespace QMapLibre;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_mapWidget(nullptr),
    m_configManager(new LayerConfigManager(this))
{
    ui->setupUi(this);
    setupMap();
    updateLayerList();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setupMap()
{
    // 创建MapLibre地图控件
    Settings settings;
    settings.setApiBaseUrl(QStringLiteral("https://api.mapbox.com"));
    m_mapWidget = new GLWidget(settings);
    //ui->mapWidget
    

    ui->mapLayout->addWidget(m_mapWidget);

    
    
    // 暂时注释掉设置地图中心和缩放级别的代码，等待确认正确的API方法
    // QMapLibre::Coordinate centerCoord(39.9042, 116.4074); // 北京
    // m_mapWidget->map()->setCenter(centerCoord);
    // m_mapWidget->map()->setZoom(10.0);
    
    // 使用默认样式URL
    m_mapWidget->map()->setStyleUrl(QStringLiteral("https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL"));
}

void MainWindow::updateLayerList()
{
    ui->layerList->clear();
    
    for (const MapLayer &layer : m_layers) {
        QListWidgetItem *item = new QListWidgetItem(layer.name(), ui->layerList);
        item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
        item->setCheckState(layer.isVisible() ? Qt::Checked : Qt::Unchecked);
        
        // 存储图层信息
        QVariant data;
        data.setValue(layer);
        item->setData(Qt::UserRole, data);
    }
    
    // 更新按钮状态
    on_layerList_itemSelectionChanged();
}

void MainWindow::updateLayerVisibility(const QString &layerId, bool visible)
{
    // 暂时简化图层可见性更新方法，等待确认正确的API
    qDebug() << "Update layer visibility:" << layerId << visible;
    // 后续确认正确的API方法后再实现
}

void MainWindow::addLayerToMap(const MapLayer &layer, int /*index*/)
{
    QString sourceId = "source_" + layer.name().replace(" ", "_");
    QString layerId = "layer_" + layer.name().replace(" ", "_");
    
    // 创建数据源
    QJsonObject sourceObj;
    switch (layer.type()) {
    case MapLayer::GridLayer: {
        sourceObj["type"] = "raster";
        sourceObj["tiles"] = QJsonArray() << layer.source();
        sourceObj["tileSize"] = 256;
        break;
    }
    case MapLayer::MBTilesLayer: {
        sourceObj["type"] = "vector";
        sourceObj["url"] = "mbtiles://" + layer.source();
        break;
    }
    case MapLayer::AmapLayer: 
    case MapLayer::TianDiTuLayer: {
        sourceObj["type"] = "raster";
        sourceObj["tiles"] = QJsonArray() << layer.source();
        sourceObj["tileSize"] = 256;
        break;
    }
    default:
        return;
    }
    
    // 暂时简化添加数据源的方法，等待确认正确的API
    qDebug() << "Adding source:" << sourceId;
    // 后续确认正确的API方法后再实现完整功能
    // QVariantMap sourceMap = QJsonDocument(sourceObj).toVariant().toMap();
    // m_mapWidget->map()->addSource(sourceId, sourceMap);
    
    // 创建图层
    QJsonObject layerObj;
    layerObj["id"] = layerId;
    layerObj["type"] = (layer.type() == MapLayer::MBTilesLayer) ? "line" : "raster";
    layerObj["source"] = sourceId;
    
    if (layer.type() == MapLayer::MBTilesLayer) {
        layerObj["source-layer"] = "data";
        
        // 添加样式
        QJsonObject paintObj;
        paintObj["line-color"] = "#888888";
        paintObj["line-width"] = 1.0;
        layerObj["paint"] = paintObj;
    }
    
    // 设置可见性
    layerObj["layout"] = QJsonObject({{"visibility", layer.isVisible() ? "visible" : "none"}});
    
    // 暂时简化添加图层的方法，等待确认正确的API
    QString currentLayerId = layerObj["id"].toString();
    qDebug() << "Adding layer:" << currentLayerId;
    // 后续确认正确的API方法后再实现完整功能
    // m_mapWidget->map()->addLayer(currentLayerId, QJsonDocument(layerObj).toVariant().toMap(), beforeLayerId);
}

void MainWindow::removeLayerFromMap(QString layerId)
{
    // 暂时简化移除图层的方法，等待确认正确的API
    QString layerIdFormatted = "layer_" + layerId.replace(" ", "_");
    QString sourceIdFormatted = "source_" + layerId.replace(" ", "_");
    qDebug() << "Removing layer:" << layerIdFormatted << "and source:" << sourceIdFormatted;
    // 后续确认正确的API方法后再实现完整功能
    // m_mapWidget->map()->removeLayer(layerIdFormatted);
    // m_mapWidget->map()->removeSource(sourceIdFormatted);
}

void MainWindow::reorderLayers()
{
    // 暂时简化重新排序图层的方法，等待确认正确的API
    qDebug() << "Reordering layers:" << m_layers.size();
    // 后续确认正确的API方法后再实现完整功能
    // for (const MapLayer &layer : m_layers) {
    //     removeLayerFromMap(layer.name());
    // }
    // 
    // for (int i = 0; i < m_layers.size(); i++) {
    //     addLayerToMap(m_layers[i], i);
    // }
}

void MainWindow::on_addLayerButton_clicked()
{
    LayerConfigDialog dialog(this);
    if (dialog.exec() == QDialog::Accepted) {
        MapLayer newLayer = dialog.layer();
        
        // 检查图层名称是否重复
        for (const MapLayer &layer : m_layers) {
            if (layer.name() == newLayer.name()) {
                QMessageBox::warning(this, tr("警告"), tr("图层名称已存在！"));
                return;
            }
        }
        
        // 添加图层到列表
        m_layers.append(newLayer);
        
        // 添加图层到地图
        addLayerToMap(newLayer, m_layers.size() - 1);
        
        // 更新图层列表
        updateLayerList();
    }
}

void MainWindow::on_removeLayerButton_clicked()
{
    int currentRow = ui->layerList->currentRow();
    if (currentRow < 0 || currentRow >= m_layers.size()) {
        return;
    }
    
    // 从地图中移除图层
    removeLayerFromMap(m_layers[currentRow].name());
    
    // 从列表中移除图层
    m_layers.removeAt(currentRow);
    
    // 更新图层列表
    updateLayerList();
}

void MainWindow::on_layerList_itemSelectionChanged()
{
    bool hasSelection = (ui->layerList->currentRow() >= 0);
    ui->removeLayerButton->setEnabled(hasSelection);
    ui->moveUpButton->setEnabled(hasSelection && (ui->layerList->currentRow() > 0));
    ui->moveDownButton->setEnabled(hasSelection && (ui->layerList->currentRow() < ui->layerList->count() - 1));
    ui->visibilityCheckBox->setEnabled(hasSelection);
    
    if (hasSelection) {
        QListWidgetItem *item = ui->layerList->currentItem();
        ui->visibilityCheckBox->setChecked(item->checkState() == Qt::Checked);
    }
}

void MainWindow::on_moveUpButton_clicked()
{
    int currentRow = ui->layerList->currentRow();
    if (currentRow <= 0) {
        return;
    }
    
    // 交换图层顺序
    m_layers.swap(currentRow, currentRow - 1);
    
    // 重新排序地图上的图层
    reorderLayers();
    
    // 更新列表
    updateLayerList();
    ui->layerList->setCurrentRow(currentRow - 1);
}

void MainWindow::on_moveDownButton_clicked()
{
    int currentRow = ui->layerList->currentRow();
    if (currentRow >= m_layers.size() - 1) {
        return;
    }
    
    // 交换图层顺序
    m_layers.swap(currentRow, currentRow + 1);
    
    // 重新排序地图上的图层
    reorderLayers();
    
    // 更新列表
    updateLayerList();
    ui->layerList->setCurrentRow(currentRow + 1);
}

void MainWindow::on_visibilityCheckBox_stateChanged(int arg1)
{
    int currentRow = ui->layerList->currentRow();
    if (currentRow < 0) {
        return;
    }
    
    bool visible = (arg1 == Qt::Checked);
    
    // 更新图层可见性
    m_layers[currentRow].setVisible(visible);
    updateLayerVisibility("layer_" + m_layers[currentRow].name().replace(" ", "_"), visible);
    
    // 更新列表项
    ui->layerList->currentItem()->setCheckState(visible ? Qt::Checked : Qt::Unchecked);
}

void MainWindow::on_saveConfigButton_clicked()
{
    QString name = QInputDialog::getText(this, tr("保存配置"), tr("请输入配置名称:"));
    if (name.isEmpty()) {
        return;
    }
    
    if (m_configManager->saveConfig(name, m_layers)) {
        QMessageBox::information(this, tr("成功"), tr("配置保存成功！"));
    } else {
        QMessageBox::warning(this, tr("错误"), tr("配置保存失败！"));
    }
}

void MainWindow::on_loadConfigButton_clicked()
{
    QStringList configs = m_configManager->availableConfigs();
    if (configs.isEmpty()) {
        QMessageBox::information(this, tr("提示"), tr("没有找到保存的配置！"));
        return;
    }
    
    QString name = QInputDialog::getItem(this, tr("加载配置"), tr("请选择配置:"), configs, 0, false);
    if (name.isEmpty()) {
        return;
    }
    
    // 移除现有图层
    for (const MapLayer &layer : m_layers) {
        removeLayerFromMap(layer.name());
    }
    
    // 加载新配置
    m_layers = m_configManager->loadConfig(name);
    
    // 添加新图层到地图
    for (int i = 0; i < m_layers.size(); i++) {
        addLayerToMap(m_layers[i], i);
    }
    
    // 更新图层列表
    updateLayerList();
    QMessageBox::information(this, tr("成功"), tr("配置加载成功！"));
}